﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Xml.Serialization;
using System.IO;
using System.Reflection;
using CommunityServerRest;
using CSWriter.Blogs;

using Resources = CSWriter.Properties.Resources;
using System.Resources;

namespace CSWriter {
	public partial class Principal : Form {

		BlogManager manager;
		BlogService service;
		Settings settings = new Settings();

		public BlogInfo BlogInfo { get; set; }

		public Principal() {
			InitializeComponent();

			try {
				settings = Settings.Load();
				BlogInfo = settings.DefaultBlog;
				service = new BlogService(settings.ServiceCredentials);
			} catch {
			    settings = new Settings();
				service = new BlogService();
			}

			manager = new BlogManager(service);
		}

		private void OpenEditorForNew() {
			Editor editor = new Editor(manager, settings);
			editor.PostPublished += new Editor.PostPublishedEventHandler(editor_PostPublished);
			
			editor.ShowDialog();
			editor.PostPublished -= new Editor.PostPublishedEventHandler(editor_PostPublished);
		}

		private void OpenEditorForEditing(BlogPostItem postToEdit) {
			Editor editor = new Editor(manager, postToEdit, settings, false);
			editor.ShowDialog();
		}

		private void AbrirEditor(RecentPostEntry recent) {
			BlogPostItem postItem = manager.GetBlogPostItem(recent.Id);
			OpenEditorForEditing(postItem);
		}

		void editor_PostPublished(object sender, BlogPostItem post, string localCopyPath) {

			RecentPostEntry recent = new RecentPostEntry();
			recent.Title = post.Title;
			recent.SourceBlog = post.BlogInfo;
			recent.LocalFilename = Path.GetFileName(localCopyPath);
			recent.Id = post.Id;
			recent.Date = post.Date;

			ListViewItem entry = new ListViewItem();
			entry.Text=post.Title;
			entry.ImageIndex=1;
			entry.Tag = recent;

			listView2.Items.Insert(0, entry);
			settings.RecentPosts.RecentPostEntries.Add(recent);
		}

		private void EscribirNuevo_Click(object sender, EventArgs e) {
			OpenEditorForNew(); 
		}

		private BlogPostItem CargarArtículo(string path) {

			XmlSerializer serializer = new XmlSerializer(typeof(BlogPostItem));
			StreamReader reader = new StreamReader(path);
			BlogPostItem art = (BlogPostItem)serializer.Deserialize(reader);
			reader.Close();
			return art;
		}

		private void salir_Click(object sender, EventArgs e) {
			Close();
		}

		private void Principal_Load(object sender, EventArgs e) {
			recentPanel.Height = this.ClientSize.Height/2;
			LoadRecentList();
			CargarBorradores();
		}

		private void LoadRecentList() {
			RecentPostList recentPosts = settings.RecentPosts;

			recentPosts.RecentPostEntries.Sort();
			recentPosts.RecentPostEntries.Reverse();

			foreach (RecentPostEntry entry in recentPosts.RecentPostEntries) {
				ListViewItem item = new ListViewItem();
				item.Text = entry.Title;
				item.ImageIndex = 1;
				item.Tag = entry;
				listView2.Items.Add(item);
			}
		}

		private void CargarBorradores() {
			DirectoryInfo dir = new DirectoryInfo(Settings.DraftsPath);
			if (dir.Exists) {
				FileInfo[] fi = dir.GetFiles("*" + Settings.PostExtension);
				foreach (FileInfo fileInfo in fi) {
					ListViewItem item = new ListViewItem();
					item.Text = fileInfo.Name;
					item.ImageIndex = 0;
					item.Tag = fileInfo;
					listView1.Items.Add(item);
				}
			}
		}

		private void listView1_ItemActivate(object sender, EventArgs e) {
			ListViewItem actived = listView1.Items[listView1.SelectedIndices[0]];
			string pathToOpen=((FileInfo) actived.Tag).FullName;
			OpenEditorForEditing(CargarArtículo(pathToOpen));
		}

		private void EliminarBorrador_Click(object sender, EventArgs e) {

		}

		private void opciones_Click(object sender, EventArgs e) {
			Opciones opciones = new Opciones();
			opciones.ServiceCredentials = settings.ServiceCredentials;
			if (opciones.ShowDialog() == DialogResult.OK) {
				try {
					service.Credentials = opciones.ServiceCredentials;
					settings.ServiceCredentials = opciones.ServiceCredentials;
				} catch {
					MessageBox.Show(Resources.InvalidUrl);
				}
			}
		}

		private void Principal_Closing(object sender, CancelEventArgs e) {
			settings.Save(Path.Combine(Settings.AppPath, "Settings.xml"));
			Application.Exit();
		}

		private void menuItem7_Click(object sender, EventArgs e) {
			SelectBlog selector = new SelectBlog(manager);
			selector.SelectedBlog = BlogInfo;
			if (selector.ShowDialog()== DialogResult.OK) {
				BlogInfo = selector.SelectedBlog;
				settings.DefaultBlog = BlogInfo;
			}
		}
		private void listView2_ItemActivate(object sender, EventArgs e) {
				
			ListViewItem actived = listView2.Items[listView2.SelectedIndices[0]];
			RecentPostEntry entry = (RecentPostEntry)actived.Tag;
			try {
				AbrirEditor(entry);
			} catch {
				if (MessageBox.Show(string.Concat(Resources.CouldNotLoadRemotePost, "\n", Resources.LoadLocalPostQuestion), Resources.ConnectionException, MessageBoxButtons.YesNo, MessageBoxIcon.Hand, MessageBoxDefaultButton.Button1) == DialogResult.Yes) {
			        BlogPostItem backup=CargarArtículo(Path.Combine(Settings.PostsPath, entry.LocalFilename));
			        OpenEditorForNew(backup);
			    }
			}
		}

		private void OpenEditorForNew(BlogPostItem backup) {
			Editor editor = new Editor(manager, backup, settings, true);
			editor.PostPublished += new Editor.PostPublishedEventHandler(editor_PostPublished);
			editor.ShowDialog();
			editor.PostPublished -= new Editor.PostPublishedEventHandler(editor_PostPublished);
		}
		private void manageOnlinePosts_Click(object sender, EventArgs e) {
			OnlineManager viewMore = new OnlineManager(manager);
			if (viewMore.ShowDialog() == DialogResult.OK) {
				Cursor.Current = Cursors.WaitCursor;
				try {
					BlogPostItem pI = manager.GetBlogPostItem(viewMore.SelectedPost);
					Cursor.Current = Cursors.Default;
					OpenEditorForEditing(pI);
				} catch (Exception ex) {
					Cursor.Current = Cursors.Default;
					MessageBox.Show(string.Concat(Resources.CouldNotLoadRemotePost, ex), Resources.Exception);
				}
			}
		}

		private void Principal_Activated(object sender, EventArgs e) {
			ResourceManager r = new ResourceManager(typeof(Principal));
			Text = r.GetString("$this.Text");
		}

	}
}